var WIDGET_VERSION = "1.0";
var UPDATE_URL = "http://www.jappit.com/m/bingwidget/download.php";

var checkingUpdates = false;

function checkForUpdates()
{
	if(!checkingUpdates)
	{
		checkingUpdates = true;
		
		showUpdateResult('<img src="images/ajax-loader.gif" /><br/>Checking for updates..', true);
		
		httpRequest("http://www.jappit.com/m/bingwidget/widget_updates.php?version=" + WIDGET_VERSION, updatesHandler);
	}
}
function showUpdateResult(txt, avoidHide)
{
	$('update_result').innerHTML = txt;
	
	if(!avoidHide)
		setTimeout(clearUpdateResult, 5000);
}
function clearUpdateResult()
{
	$('update_result').innerHTML = '';
}
function updatesHandler(responseText)
{
	if(responseText)
	{
		if(responseText != 'NO UPDATES')
		{
			if(responseText == 'NEWVER')
			{
				showUpdateResult("");
				
				new Popup("A new version of the Bing widget is available. Do you want to download it now?", "Yes", downloadNewVersion, "No", null).show();
			}
			else
			{
				addNewCode(responseText);
			
				storeNewCode(responseText);
				
				showUpdateResult("Updates were correctly downloaded!");
			}
		}
		else
		{
			showUpdateResult("No updates available");
		}
	}
	else
	{
		showUpdateResult("Error while requesting the updates");
	}
	checkingUpdates = false;
}

function loadLocalUpdates()
{
	var localUpdates = widget.preferenceForKey('code_updates');

	if(localUpdates != undefined)
		addNewCode(localUpdates);
}

function storeNewCode(code)
{
	var alreadySavedCode = widget.preferenceForKey('code_updates');

	if(alreadySavedCode != undefined)
		widget.setPreferenceForKey(alreadySavedCode + code, 'code_updates');
	else
		widget.setPreferenceForKey(code, 'code_updates');
}

function addNewCode(code)
{
	var scriptElement = document.createElement('script');
	
	var scriptContent = document.createTextNode(code);
	
	scriptElement.appendChild(scriptContent);
	
	document.body.appendChild(scriptElement);
}

function downloadNewVersion()
{
	widget.openURL(UPDATE_URL);
	
	window.close();
}

function httpRequest(url, handler)
{
	try
	{
		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	}
	catch(e)
	{
		
	}
		
	
	try
	{
		var request = new XMLHttpRequest();
		request.open("GET", url, true );
		request.send(null);

		request.onreadystatechange = function(){
			if(this.readyState == 4)
			{
				if(this.status == 200)
				{
					handler(request.responseText);
				}
				else
				{
					handler(false);
				}
			}
		}
	}
	catch( e )
	{
		handler(false);
	}
}